package com.aia.prm.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.Assert;

import com.aia.ilp.domain.SmsLog;
import com.aia.ilp.domain.SmsMsgchosend;
import com.aia.prm.config.AddressNotFoundException;
import com.aia.prm.config.ChinaAddress;
import com.aia.prm.config.CompanyCodes;
import com.aia.web1.domain.Aginf;
import com.aia.web1.domain.Aginf2;
import com.aia.web1.domain.Aginf2Key;
import com.aia.web1.domain.Aginf3;
import com.aia.web1.domain.Aginf3Key;
import com.aia.web1.domain.AginfKey;
import com.aia.web1.domain.Qnpe;
import com.aia.web1.domain.QnpeExample;
import com.aia.web1.web.nmp.NmpAction;
import com.cfh.ahead.Constant;
import com.cfh.domain.User;
import com.cfh.domain.UserExample;
import com.cfh.domain.UserExample.Criteria;
import com.cfh.util.Tools;

@SuppressWarnings("rawtypes")
public class DefaultServiceImpl extends AbstractDefaultService implements DefaultService {
	private static final Logger logger = Logger.getLogger(DefaultServiceImpl.class);

	public void changePassword(User currentUser, String newPassword) {
		currentUser.setPASSWORD(newPassword);
		getUserDAO().updateByPrimaryKey(currentUser);
	}

	public User getUserByUsernameAndPassword(String username, String password) {
		if (logger.isDebugEnabled()) {
			logger.debug("getUserByUsernameAndPassword(String, String) - start"); //$NON-NLS-1$
		}

		Assert.hasText(username);
		Assert.hasText(password);
		UserExample ue = new UserExample();
		Criteria ct = ue.createCriteria();
		ct.andLOGIN_NAMEEqualTo(username);
		ct.andPASSWORDEqualTo(password);
		List list = getUserDAO().selectByExample(ue);
		if (list != null && list.size() > 0) {
			User returnUser = (User) list.get(0);
			if (logger.isDebugEnabled()) {
				logger.debug("getUserByUsernameAndPassword(String, String) - end"); //$NON-NLS-1$
			}
			return returnUser;
		} else {
			return null;
		}
	}

	public void updateNmp(NmpAction action) {
		ChinaAddress add = null;
		try {
			add = CompanyCodes.translateToAddress(action.getAddress());
		} catch (AddressNotFoundException e) {
			logger.error("传入的省市参数错误", e);
			action.addActionError("传入的省市参数错误");
			return;
		}

		if (!Tools.hasText(action.getPho())) {
			action.addActionError("手机号为空");
			return;
		}
		final String from = action.getFrom();
		final String mobile = action.getPho().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QnpeExample example = new QnpeExample();
			com.aia.web1.domain.QnpeExample.Criteria criteria = example.createCriteria();
			criteria.andQNXE_PHOEqualTo(mobile);
			if(StringUtils.isNotBlank(from)){
				criteria.andQNXE_FROMEqualTo(from);
			}
			List list = getQnpeDAO().selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("您已经提交过，请勿重复提交，感谢您的参与！");
				return;
			}
		}
		String code = action.getCode();
		if (StringUtils.isEmpty(code)) {
			code = "999999999";
		}
		code = StringUtils.leftPad(code, 9, "0");
		Qnpe record = new Qnpe();
		record.setQNXE_ADRESS(action.getAddress());
		record.setQNXE_CODE(code);
		record.setQNXE_NAME(action.getName());
		record.setQNXE_PHO(action.getPho());
		record.setQNXE_GUID(Tools.GUID());
		record.setQNXE_DATE(Tools.getToday());
		record.setQNXE_TIME(Tools.getTime());
		record.setQNXE_FREETEXT3(add.getCompanyCode());
		record.setQNXE_FREETEXT4(add.getProviceName());
		record.setQNXE_PROVINCE(add.getProvinceCode());
		record.setQNXE_CITY(add.getCityCode());
		record.setQNXE_DISTRICT(add.getDistCode());
		record.setQNXE_VALIDATE(action.getValidate());
		record.setQNXE_FROM(from);
		record.setQNXE_FREETEXT1(action.getEmail());
		record.setQNXE_FREETEXT2(action.getIdnumber());
		
		record.setQNXE_FREETEXT5(action.getLang()); //常用语言
		record.setQNXE_FREETEXT6(action.getBirthm()); //生日-月
		record.setQNXE_BIRTH(action.getBirthy()); //生日-年
		record.setQNXE_SEX(action.getSex()); //性别
		qnpeDAO.insert(record);
		removeCaptcha();

		logger.debug("print from=" + from);
		if ("xingfu".equals(from)) {
			try {// 发短信给agent
				Aginf2Key key2 = new Aginf2Key();
				key2.setAGI_CITYCODE(add.getCityCode());
				key2.setAGI_PROVINCECODE(add.getProvinceCode());
				key2.setAGI_CODE(code);
				Aginf2 aginf2 = aginf2DAO.selectByPrimaryKey(key2);
				if (aginf2 != null && StringUtils.isNotEmpty(aginf2.getAGI_PHONE()) && aginf2.getAGI_PHONE().length() == 11) {
					SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
					String today = formatter.format(new Date());

					String msg = record.getQNXE_NAME() + " " + record.getQNXE_PHO() + " " + today + "参与了[幸福人生 至真生活]活动";
					sendSMS(msg, aginf2.getAGI_PHONE(), from);
				}
			} catch (Exception e) {
				logger.error("发AGENT短信出错-xingfu", e);
			}
		} else if ("JS-summer".equals(from)) {
			try {// 发短信给agent
				Aginf3Key key2 = new Aginf3Key();
				key2.setAGI_CITYCODE(add.getCityCode());
				key2.setAGI_PROVINCECODE(add.getProvinceCode());
				key2.setAGI_CODE(code);
				Aginf3 aginf2 = aginf3DAO.selectByPrimaryKey(key2);
				if (aginf2 != null && StringUtils.isNotEmpty(aginf2.getAGI_PHONE()) && aginf2.getAGI_PHONE().length() == 11) {
					SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
					String today = formatter.format(new Date());

					String msg = record.getQNXE_NAME() + " " + record.getQNXE_PHO() + " " + today + "参与了友邦江苏 [“悦”动夏日，“佑”惑无限 ]活动";
					sendSMS(msg, aginf2.getAGI_PHONE(), from);
				}
			} catch (Exception e) {
				logger.error("发AGENT短信出错-JS-summer", e);
			}
		} else if ("xingui".equals(from)) {
			logger.debug("skip send sms for:" + from);
		} else if ("dm".equals(from)) {
			logger.debug("skip send sms for:" + from);
		} else if ("SOS".equals(from)) {
			logger.debug("skip send sms for:" + from);
		} else {
			if (Tools.hasText(from)) {
				logger.warn("Invalid From, skip it and using default logic!");
			}
			try {// 发短信给agent
				AginfKey key = new AginfKey();
				key.setAGI_CITYCODE(add.getCityCode());
				key.setAGI_PROVINCECODE(add.getProvinceCode());
				key.setAGI_CODE(code);
				Aginf aginf = aginfDAO.selectByPrimaryKey(key);
				if (aginf != null && StringUtils.isNotEmpty(aginf.getAGI_PHONE()) && aginf.getAGI_PHONE().length() == 11) {
					SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
					String today = formatter.format(new Date());
					// 短信内容为：[用户输入的姓名]+[用户输入的手机号码]+[日期]+“参与了新医疗保障计划活动”
					String msg = record.getQNXE_NAME() + " " + record.getQNXE_PHO() + " " + today + "参与了"+from+"活动";
					sendSMS(msg, aginf.getAGI_PHONE(), "nmp");
				}
			} catch (Exception e) {
				logger.error("发AGENT短信出错-nmp", e);
			}

		}
	}

	private void removeCaptcha() {
		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			if (session != null) {
				session.setAttribute(Constant.CAPTCHA_SESSION_HOLDER, "");
			}
		} catch (Exception e) {
			logger.warn("removeCaptcha:" + e, e);
		}
	}

	private void sendSMS(String msg, String mobile, String remark) {
		try {
			try {
				// 插入SMSLOG表
				SmsLog smslog = new SmsLog();
				smslog.setSMSLOG_GUID(Tools.GUID());
				smslog.setSMSLOG_DATE(Tools.getToday());
				smslog.setSMSLOG_TIME(Tools.getTime());
				smslog.setSMSLOG_MOBILE(mobile);
				smslog.setSMSLOG_FREETEXT1(remark);
				smsLogDAO.insertSelective(smslog);
			} catch (Exception e) {
				logger.error("SMSLOG表出错", e);
			}
			int msgNo = 0;
			String msgType = "N";
			String msg1 = "";
			String msg2 = "";
			String msg3 = "";
			if (msg.length() <= 60) {
				msgNo = 1;
				msgType = "N";
				msg1 = msg;
			} else if (msg.length() > 60 && msg.length() <= 120) {
				msgNo = 2;
				msgType = "Y";
				msg1 = msg.substring(0, 60) + "（1）";
				msg2 = msg.substring(60) + "（2）";
			} else if (msg.length() > 120) {
				msgNo = 3;
				msgType = "Y";
				msg1 = msg.substring(0, 60) + "（1）";
				msg2 = msg.substring(60, 120) + "（2）";

				if (msg.length() > 180) {
					logger.warn("短信长度大于180");
					msg3 = msg.substring(120, 180) + "（3）";
				} else {
					msg3 = msg.substring(120) + "（3）";
				}
			}

			// 发短信
			SmsMsgchosend smssend = new SmsMsgchosend();
			smssend.setMSGCO("0986");
			smssend.setMSGAGT("000000000");
			smssend.setMSGPOLN("ILP0000000");
			smssend.setMSGMSAG01(msg1);// 多条短信!
			smssend.setMSGMSAG02(msg2);// 多条短信!
			smssend.setMSGMSAG03(msg3);
			smssend.setMSGTYPE(msgType);// 多条短信!
			smssend.setMSGNO(msgNo); // 多条短信!
			smssend.setMSGFUNC("T04S01");
			smssend.setMSGDATE(new Date());
			smssend.setMSGUSER("eStore_ILP");
			smssend.setMSGSTS("S");
			smssend.setMSGMBNUM(mobile);
			smssend.setMSGFL01("");
			smssend.setMSGFL02("");
			smssend.setMSGFL03("");
			smssend.setMSGFL04(0);
			smsMsgchosendDAO.insertSelective(smssend);
			if (logger.isDebugEnabled()) {
				logger.debug("Print SMS>" + msg);
			}
		} catch (Exception e) {
			logger.error("发短信失败", e);
		}

	}
}
